package com.spark.security.handle;

import com.alibaba.fastjson.JSON;
import com.spark.common.constants.Constants;
import com.spark.common.core.Result;
import com.spark.common.core.entity.LoginUser;
import com.spark.common.manager.AsyncManager;
import com.spark.common.manager.factory.AsyncLogFactory;
import com.spark.common.utils.JwtUtils;
import com.spark.common.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 自定义退出处理类 返回成功
 *
 * @author LYCHEE
 * @date 2025/2/18 14:43
 */
@Slf4j
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    @Resource
    private JwtUtils jwtUtils;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        LoginUser loginUser = jwtUtils.getLoginUser(request);
        if (Objects.nonNull(loginUser)) {
            String username = loginUser.getUsername();
            // 删除用户缓存
            jwtUtils.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncLogFactory.createLoginLog(username, Constants.LOGIN_SUCCESS, "退出登录成功"));
        }
        ServletUtils.renderString(response, JSON.toJSONString(Result.ok("退出成功")));
    }

}
